package com.kdd.campus.common.util;

import com.kdd.campus.common.entity.FastDFSFile;
import org.csource.common.MyException;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @Auther: fcp
 * @Date: 2020/1/31 13:24
 * @Description:
 */
public class FastDFSClient {

    private static Logger logger = LoggerFactory.getLogger(FastDFSClient.class);

    /**
     * 初始化加载FastDFS的TrackerServer配置
     */
    static {
        try {
//            String filePath = new ClassPathResource("fdfs_client.conf").getFile().getAbsolutePath();
            String filePath = new ClassPathResource("fdfs_client.conf").getPath();
            ClientGlobal.init(filePath);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (MyException e) {
            logger.error("FastDFS Client init fail",e);
            e.printStackTrace();
        }
    }


    /**
     * 文件上传
     */
    public static String[] upload(FastDFSFile file){
        // 获取文件的作者
        NameValuePair[] meta_list = new NameValuePair[1];
        meta_list[0] = new NameValuePair("author" , file.getAuthor());

        // 接受返回数据
        String[] uploadResults = null;
        StorageClient storageClient = null;

        try {
            // 获取StorageClient客户端
            storageClient = getStorageClient();
            /**
             * 文件上传
             * 1） 文件字节数组
             * 2） 文件扩展名
             * 3） 文件作者
             */
            uploadResults = storageClient.upload_file(file.getContent(),file.getExt(),meta_list);

        } catch (Exception e) {
            logger.error("Exception when uploading the file : " + file.getName() , meta_list);
            e.printStackTrace();
        }

        if (uploadResults == null && storageClient != null){
            logger.error("upload file fail , error code : " + storageClient.getErrorCode());
        }

        // 获取组名
        String groupName = uploadResults[0];

        // 获取文件存储路径
        String remoteFileName = uploadResults[1];
        return uploadResults;
    }

    /**
     * 获取文件信息
     * @param groupName：组名
     * @param remoteFileName：文件存储完整名
     * @return
     */
    public static FileInfo getFile(String groupName , String remoteFileName){
        StorageClient storageClient = null;
        try {
            storageClient = getStorageClient();
            return storageClient.get_file_info(groupName, remoteFileName);
        } catch (Exception e) {
            logger.error("Exception: Get File from Fast DFS failed", e);
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 文件下载
     * @param groupName
     * @param remoteFileName
     * @return
     */
    public static InputStream downFile(String groupName , String remoteFileName){
        StorageClient storageClient = null;
        try {
            storageClient = getStorageClient();
            // 下载文件
            byte[] bytes = storageClient.download_file(groupName, remoteFileName);
            ByteArrayInputStream ins = new ByteArrayInputStream(bytes);
            return ins;
        } catch (Exception e) {
            logger.error("Exception: Get File from Fast DFS failed", e);
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 文件删除
     * @param groupName
     * @param remoteFileName
     */
    public static void deleteFile(String groupName ,String remoteFileName){
        StorageClient storageClient = null;
        try {
            storageClient = getStorageClient();
            // 删除文件
            int i = storageClient.delete_file(groupName, remoteFileName);
            if (i != 0){
                logger.error("delete file fail , error code : " + storageClient.getErrorCode());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取storage组
     * @param groupName
     * @return
     */
    public static StorageServer[] getStorages(String groupName) throws IOException {
        TrackerClient trackerClient = new TrackerClient();
        // 获取TrackerServer
        TrackerServer trackerServer = trackerClient.getConnection();
        // 获取storage组
        return trackerClient.getStoreStorages(trackerServer, groupName);
    }

    /**
     * 获取storage信息，IP和端口
     *
     */
    public static ServerInfo[] getFetchStorages(String groupName , String remoteFileName) throws IOException {
        TrackerClient trackerClient = new TrackerClient();
        TrackerServer trackerServer = trackerClient.getConnection();
        return trackerClient.getFetchStorages(trackerServer, groupName, remoteFileName);
    }

    public static String getTrackerUrl() throws IOException {
        return "http://" + getTrackerServer().getInetSocketAddress().getHostString() + ":"
                + ClientGlobal.getG_tracker_http_port() + "/";
    }

    /**
     * 获取storageClient客户端
     * @return
     * @throws IOException
     */
    private static StorageClient getStorageClient() throws IOException {
        TrackerServer trackerServer = getTrackerServer();
        StorageClient storageClient = new StorageClient(trackerServer, null);
        return storageClient;
    }

    /**
     * 获取Tracker
     * @return
     */
    private static TrackerServer getTrackerServer() throws IOException {
        TrackerClient trackerClient = new TrackerClient();
        TrackerServer trackerServer = trackerClient.getConnection();
        return trackerServer;
    }

    public static void main(String[] args) throws IOException, MyException {
//        TrackerClient trackerClient = new TrackerClient();
//        TrackerServer trackerServer = trackerClient.getConnection();
//        StorageClient storageClient = new StorageClient(trackerServer, null);
//        byte[] storagegroups = storageClient.download_file("storagegroup", "M00/00/00/wKhbgV40JO2AeEZRAAcYcB1EUCM454.png");
//        InputStream byteArrayInputStream = new ByteArrayInputStream(storagegroups);
//        FileOutputStream outputStream = new FileOutputStream("D:/1.jpg");
//
//        byte[] buffer = new byte[1024];
//        int len = -1;
//        while ((len = byteArrayInputStream.read(buffer)) != -1){
//            outputStream.write(buffer , 0 , len);
//        }
//        outputStream.close();
//        byteArrayInputStream.close();

        // 删除文件
//        TrackerClient trackerClient = new TrackerClient();
//        TrackerServer trackerServer = trackerClient.getConnection();
//        StorageClient storageClient = new StorageClient(trackerServer, null);
//        storageClient.delete_file("storagegroup","M00/00/00/wKhbgV40JO2AeEZRAAcYcB1EUCM454.png");

        // 获取storage组的信息
//        TrackerClient trackerClient = new TrackerClient();
//        TrackerServer trackerServer = trackerClient.getConnection();
//        StorageServer storeStorage = trackerClient.getStoreStorage(trackerServer);
//        System.out.println(storeStorage.getStorePathIndex());
//        System.out.println(storeStorage.getInetSocketAddress().getAddress());
//        System.out.println(storeStorage.getInetSocketAddress().getHostName());
//        System.out.println(storeStorage.getInetSocketAddress().getHostString());

        // 获取tracker的ip地址和端口
        TrackerClient trackerClient = new TrackerClient();
        TrackerServer trackerServer = trackerClient.getConnection();
        System.out.println(trackerServer.getInetSocketAddress().getHostString());
        System.out.println(trackerServer.getInetSocketAddress().getPort());
        System.out.println(ClientGlobal.getG_tracker_http_port());


    }

}
